#自定义参数绘制图片
import math
import os
import warnings
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

TUNNEL = 1 #通道奇偶 1=奇数，2=偶数
SAMP = 0    #0-原始采样，1-分钟采样，2-小时采样
COPY = 1    #小于等于0的数据是否替换为上一个，值为1开启
TITLE = '5305轨道顺槽数据对比'#运输   轨道
SAVE_PATH = "C:\\Users\\11509\\Desktop\\20240126\\c\\3-1\\"    #图片保存路径

def graphPrinter(group, date, days, label):
    save_path = "C:\\Users\\DELL\\Desktop\\workspace\\"
    #SAMP = 0
    warnings.filterwarnings("ignore", category=UserWarning)
    ilabel = [',1.2mm',',1.2mm',',1.5mm',',1.2mm']
    #save_path = SAVE_PATH + '1'#TITLE
    if SAMP == 1:
        slimp = 4
    elif SAMP == 2:
        slimp = 240
    else:
        slimp = 1
    mpl.rcParams['font.size'] = 18
    plt.figure(figsize=(20, 7))
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    #plt.title(TITLE)
    plt.ylabel("Mpa")
    x = np.arange(0, len(group[0]))
    plt.xlim(0, days * 5760 / slimp)  # 分钟除以4 小时除以240
    plt.xticks(np.arange(0, len(x) + 1, 5760 / slimp), date)#, rotation=45
    maxLim = 0
    minLim = math.inf
    for i in range(len(group)):
        prev_value = None
        content = []
        for y in group[i]:
            y = float(y)
            if y > 0:
                if y > maxLim:
                    maxLim = y
                if y < minLim:
                    minLim = y
                content.append(y)
                prev_value = y
            elif y <= 0:
                if COPY == 1:
                    content.append(prev_value)
                else:
                    content.append(0)
        plt.plot(x, content, label=label[i]+'-'+str(TUNNEL))#+ilabel[i]
    plt.ylim(minLim - 0.2, maxLim + 0.2)
    plt.yticks(np.arange(math.floor(minLim), maxLim + 0.2, 1))
    plt.legend(loc='upper left', bbox_to_anchor=(1, 1), fontsize=10)
    #plt.savefig(save_path)
    plt.show()
    #print(type(plt))
    #return plt
    #plt.show()
def mySlimping(lines,index):
    #根据slimp值决定数据采样率
    #slimp：0-原始采样，1-分钟采样，2-小时采样
    #分钟和小时采样时，遇到小于等于0的值将替换为上一个值
    content = []
    time = 0
    if SAMP == 1:
        time = 4
    if SAMP == 2:
        time = 240
    if SAMP == 0:      #原始采样
        content = [line.split(',')[index-1] for line in lines]
    if time != 0:    #分钟采样，4个为一组
        t1 = 0
        n = 0
        i = 0
        for line in lines:
            t2 = float(line.split(',')[index-1])
            if t2 > 0:
                n += 1
                t1 += t2
            if i % time == 0:
                if n == 0:
                    content.append(0)
                else:
                    content.append(t1/n)
                n = 0
                t1 = 0
            i += 1
    return content

def read_stressFile(stressFile,name,foldPath):
    #sampling：0-原始采样，1-分钟采样，2-小时采样
    file_path = foldPath+"/"+name+"/"+stressFile
    try:
        with open(file_path, 'r') as file:
            # 读取第二行开始所有的内容
            lines = file.readlines()[1:]
            content = mySlimping(lines,TUNNEL%2)
            return content
    except FileNotFoundError:
        print(f"文件 {file_path} 未找到.")
        return None
def get_file_names(foldPath):
    #获取目录下所有通道名称
    filenames = []
    for filename in os.listdir(foldPath):
        filenames.append(filename)
    return filenames
def get_fileByname(name,folder,dates):
    #根据通道名称获取文件夹下所有数据内容
    stressFile = []
    for foldername, subfolders, filenames in os.walk(folder):
        for filename in filenames:
            if name in filename:
                for date in dates:
                    if '' + name + '_' + date in filename:
                        stressFile.append(filename)
    return stressFile
def complete_date_list(date_list):
    #根据开始和结束日期补完中间日期
    # 将字符串转换为datetime对象
    dates = [datetime.strptime(date, '%Y-%m-%d') for date in date_list]
    # 获取第一个日期和最后一个日期
    start_date = dates[0]
    end_date = dates[1]
    # 创建一个空的列表来保存补全的日期
    completed_dates = []
    # 循环从开始日期到结束日期，每次增加一天，并将日期添加到列表中
    current_date = start_date
    if current_date>end_date:
        raise ValueError("结束日期不能早于开始日期！")
    while current_date <= end_date:
        completed_dates.append(current_date.strftime('%Y-%m-%d'))
        current_date += timedelta(days=1)
    return completed_dates

def initData(folder,tunnel,station,dates):
    global TITLE,TUNNEL
    TUNNEL = tunnel
    dates = complete_date_list(dates)
    if folder:  # 选择了文件夹
        foldNames = get_file_names(folder)
        group = []  # 组数组
        label = []
        for name in foldNames:
            if name in station:
                stressFile = get_fileByname(name, folder,dates)
                if len(stressFile) == 0:
                    raise ValueError("没有找到对应日期的数据文件！")
                label.append(name)
                dateContent = []
                stressContent = []
                stressContent1 = []
                days = len(stressFile)
                for file in stressFile:
                    dateContent.append(file[file.find("_") + 1:file.find(".")])
                    content = read_stressFile(file, name, folder)
                    stressContent+=content
                dateContent.append("次日")
                group.append(stressContent)
                date = dateContent
        days = len(date) - 1
        graphPrinter(group, date, days, label)

        #return group,date,days,label